<template>
  <view class="container">
    <!-- 顶部安全区域占位 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets.top - 10 + 'px' }"></view>

    <!-- 房间成员（折叠面板） -->
    <view v-if="isLoading">
      <uni-collapse>
        <uni-collapse-item title="房间成员" :open="true" :show-arrow="false" :title-border="'none'">
          <view>正在加载房间成员信息...</view>
        </uni-collapse-item>
      </uni-collapse>
    </view>
    <view v-else>
      <uni-collapse>
        <uni-collapse-item title="房间成员" :open="true" :show-arrow="false" :title-border="'none'">
          <view class="content fade-in">
            <view class="user" v-for="(member, userId) in members" :key="userId">
              <image :src="member.avatar" class="avatar"></image>
              <text class="username">{{ member.nickname || member.name }}</text>
            </view>
          </view>
        </uni-collapse-item>
      </uni-collapse>
    </view>

    <!-- 对局记录（消息卡片） -->
    <view class="custom-card" v-for="(record, index) in history" :key="index">
      <view class="card-time">
        <text class="card-text">{{ record.time }} · 第{{ index + 1 }}局</text>
      </view>
      <view class="card-score">
        <view class="card-item" v-for="(score, userId) in record.scores" :key="userId">
          <image src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png"></image>
          <text class="card-text">{{ score }}</text>
        </view>
      </view>
    </view>

    <!-- 底部功能区域 -->
    <view class="foot fade-in">
      <button class="footbutton-left" @click="handleSettleRound" :disabled="!isConnected">
        <text> 结算本局 </text>
      </button>

      <image class="share" src="@/static/user.png"></image>

      <button class="footbutton-right" @click="handleLeaveRoom" :disabled="!isConnected">
        离开房间
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useSocketStore } from '@/stores/modules/socketStore.js'; // 引入封装的Socket Store

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();

// 使用 Pinia store
const socketStore = useSocketStore();

// 使用 storeToRefs 解构出需要响应式的状态
const { 
  currentMembers: members, // 房间人员
  currentHistory: history,// 对局记录
  currentRoomId: roomId,
  connectionState,
  isConnectedToRoom,
  isConnecting,
  hasError
} = storeToRefs(socketStore);


// 计算属性 - 用于判断折叠面板记载开关是否正在加载
const isLoading = computed(() => {return   Object.keys(members.value).length === 0})
// const isLoading = computed(() => isConnecting.value || !isConnectedToRoom.value(roomId.value));
// const isLoading = ref(false);
const isConnected = computed(() => socketStore.connectionState === 'connected');

// onload:页面首次加载时触发,初始化页面数据或获取传递的参数
// onMounted：Vue 组件挂载到 DOM 后触发,操作 DOM 或初始化依赖 DOM 的逻辑
// 页面加载时获取房间ID并连接
onLoad((options) => {
	console.log("onLoad")
  roomId.value = options.room_id;
  if (roomId.value) {
    connectToRoom();
	// socketStore.emit('init_room', { room_id: roomId.value});
	// refreshRoomData();
  } else {
    uni.showToast({ title: '未获取到房间ID', icon: 'none' });
  }
});
// 页面显示时执行（从其他页面返回时）
// onShow(() => {
//   // refreshRoomData(); 
// });





// 连接到房间
const connectToRoom = async () => {
  try {
    await socketStore.connect(roomId.value); // 调用Store的连接方法
    console.log('连接房间成功:', roomId.value);
  } catch (err) {
    uni.showToast({ title: '连接失败: ' + err.message, icon: 'none' });
    console.error('连接错误:', err);
  }
};
// 折叠面板数据初始化
// const refreshRoomData = () => {
//   if (!roomId.value) return;
//   isLoading.value = true;
//   socket.value.emit('init_room', { room_id: roomId.value });
// };
// 处理结算本局
const handleSettleRound = async () => {
  try {
    const res = await uni.request({
      url: `http://172.16.24.120:5000/mysqlroom/get_room_info/${roomId.value}`,
      method: 'GET'
    });
    uni.navigateTo({
      url: `/pages/room/roundpay?roomId=${roomId.value}&roundNumber=${res.data.current_game}`
    });
  } catch (err) {
    uni.showToast({ title: '获取房间信息失败', icon: 'none' });
  }
};

// 处理离开房间
const handleLeaveRoom = async () => {
  socketStore.leaveRoom(roomId.value); // 清理房间数据
  socketStore.disconnect(); // 断开连接
  uni.navigateBack();
};

// 注册事件监听（组件挂载时）
onMounted(() => {
	console.log("onMounted")
  // 监听历史记录更新（可选，Store已自动同步数据）——————该页面独有的事件放到这里监听？   还是统一管理数据组件只展示？
  socketStore.on('history_update', (data) => {
    if (data.room_id === roomId.value) {
      console.log('历史记录更新:', data.history);
    }
  });
  
  
  
  
});

// 移除事件监听（组件卸载时）
onUnmounted(() => {
  socketStore.off('history_update'); // 清理监听
  // 若需要完全断开连接（根据业务场景）
  // if (socketStore.currentRoomId === roomId.value) {
  //   socketStore.disconnect();
  // }
});
</script>

<style>
/* 样式保持不变 */
.navbar {
  /* 安全区域样式 */
}
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
.content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
}
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.user {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 13px;
}
.custom-card {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  padding: 20px;
  margin: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  background-color: #fff;
  border-radius: 8px;
}
.card-time {
  margin-bottom: 20px;
}
.card-score {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
.card-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 26px;
}
.card-text {
  font-size: 14px;
  color: #a0a6a7;
  text-align: center;
}
.card-item image {
  width: 42px;
  height: 42px;
  margin-bottom: 5px;
  border-radius: 10%;
}
.foot {
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.footbutton-left {
  background-color: #8b8a84;
  color: white;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  width: 125px;
  height: 60px;
  font-size: 18px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.footbutton-right {
  background-color: #41403b;
  color: white;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  width: 125px;
  height: 60px;
  font-size: 18px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.share {
  width: 60px;
  height: 60px;
  object-fit: contain;
}
.share:hover {
  transform: scale(1.3);
}
.footbutton-left:hover,
.footbutton-right:hover {
  background-color: #0056b3;
}
.fade-in {
  animation: fadeIn 0.3s ease-in-out;
}
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>